<?php
/**
 * Created by PhpStorm.
 * User: xiaomeng
 * Date: 17-7-13
 * Time: 上午10:23
 */
namespace mphp\Socket;
use mphp\Core\syncDb;
class Task
{

    /**
     * message:
     * cmd:string 指令
     * target_type:string   users 给用户发消息。chatgroups: 给群发消息，chatrooms: 给聊天室发消息
     * to: array 注意这里需要用数组，数组长度建议不大于20，即使只有一个用户，也要用数组 ['u1']，给用户发送时数组元素是用户名，给群组发送时,数组元素是groupid
     * msg_body:array 消息内容
     * from:string 表示消息发送者。无此字段Server会默认设置为"from":"admin"，有from字段但值为空串("")时请求失败
     * @param $server
     * @param $frame
     */
    public static function rTask($server, $task_id,$src_worker_id,$data)
    {
        sleep(0.3);

        //在线用户的fd
        $online = syncDb::redis()->get('chat_online');
        $online = json_decode($online,true);
        //讲传送过来的数据转换成数组
        $data = json_decode($data,true);
        //发送消息的用户名
        $fromuser =array_search($data['fd'],$online);

        //接受消息的目标类型
        $target_type = $data['target_type'];
        //接受消息的人
        $tousers = [];

        switch($target_type)
        {
            case 'users':
                $tousers[] = $data['to'];
                break;

            case 'chatgroups'://获取成员用户名
//                $users = syncDb::redis()->get('chat_group_users_'.$data['to']);
                $res = syncDb::collection('lqhn_groups')->where(['id'=>$data['to']])->field('owner,admin,members')->find();
                $tousers[] = $res['owner'];
                foreach($res['admin'] as $v)
                {
                    $tousers[] = $v;
                }
                foreach($res['members'] as $v)
                {
                    $tousers[] = $v;
                }
                break;

            case 'chatrooms'://获取成员用户名

                $res = syncDb::collection('lqhn_groups')->where(['id'=>$data['to']])->field('owner,admin,members')->find();
//                var_dump($res);
                $tousers[] = $res['owner'];
                foreach($res['admin'] as $v)
                {
                    $tousers[] = $v;
                }
                foreach($res['members'] as $v)
                {
                    $tousers[] = $v;
                }
                break;

            default:
                break;

        }

        $searchUser = array_search($fromuser,$tousers);
        if($searchUser !== false)
        {
            unset($tousers[$searchUser]);
        }


        $sendData = ['cmd'=>'acceptmsg','target_type'=>$target_type,'msg_body'=>$data['msg_body'],'from'=>$fromuser,'to'=>$data['to']];
        $sendData = json_encode($sendData,JSON_UNESCAPED_UNICODE);
        //offlinemsg
        $offlineMsgData = ['cmd'=>'offlinemsg','target_type'=>$target_type,'msg_body'=>$data['msg_body'],'from'=>$fromuser,'to'=>$data['to']];
        $offlineMsgData = json_encode($offlineMsgData,JSON_UNESCAPED_UNICODE);
        self::sendMsg($server,$online,$tousers,$sendData,$offlineMsgData);
        self::addHistory($fromuser,$data['to'],$data['msg_body'],$target_type);

    }

    /**
     * 统一发送消息
     */
    public static function sendMsg($server,$online,$tousers,$sendData,$offlineMsgData)
    {
        foreach($tousers as $user)
        {
            if(isset($online[$user]))
            {//在线
                $server->push($online[$user],$sendData);
            }
            else
            {//用户不在线
                syncDb::collection('chat_offline_msg')->add(['member'=>$user,'msg'=>$offlineMsgData,'time'=>self::getMillisecond()]);
            }
        }
        return true;

    }

    /**
     * 添加消息记录
     */
    public static function addHistory($from,$to,$sendData,$chat_type)
    {
        return syncDb::collection('chat_history_msg')->add(['from'=>$from,'to'=>$to,'msg'=>$sendData,'chat_type'=>$chat_type,'timestamp'=>self::getMillisecond()]);

    }

    public static function getMillisecond() {
        list($s1, $s2) = explode(' ', microtime());
        return sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
    }



}